﻿using Net.Sz.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/**
 * 
 * @author 失足程序员
 * @Blog http://www.cnblogs.com/shizuchengxuyuan/
 * @mail 492794628@qq.com
 * @phone 13882122019
 * 
 */
namespace Net.Sz.Framework.Util
{

    /// <summary>
    /// 每秒钟能产生 1亿 个id
    /// <para>不保证多程序重复性</para>
    /// <para>启动程序后，重复周期是 10 年,</para>
    /// <para>上一次启动和下一次启动之间重启周期是1秒钟</para>
    /// 
    /// <para>PS:</para>
    /// <para>@author 失足程序员</para>
    /// <para>@Blog http://www.cnblogs.com/shizuchengxuyuan/</para>
    /// <para>@mail 492794628@qq.com</para>
    /// <para>@phone 13882122019</para>
    /// </summary>
    public class LongId0
    {
        /// <summary>
        /// 每秒钟能产生 1亿 个id
        /// <para>不保证多程序重复性</para>
        /// <para>启动程序后，重复周期是 10 年,</para>
        /// <para>上一次启动和下一次启动之间重启周期是1秒钟</para>
        /// </summary>
        public LongId0()
        {

        }

        protected long upTime = 0;
        protected long MAXID = 999999999;
        protected long MAXHEAD = 100000000;
        protected long idHead = 0;
        protected long id = -1;

        /// <summary>
        /// 年月日时分服务器id和自增id组合的19位id
        /// </summary>
        /// <returns></returns>
        public virtual Int64 GetId()
        {
            long now = TimeUtil.CurrentTimeMillis() / 1000;
            long tmpid = 0;
            lock (this)
            {
                if (now != upTime)
                {
                    upTime = now;
                    /*相对耗时*/
                    string datekey = DateTime.Now.ToString("yyyyMMddHHmmss").Substring(3);
                    idHead = Convert.ToInt64(datekey) * MAXHEAD;
                    id = -1;
                }
                ++id;

                if (id > MAXID)
                {
                    throw new Exception("超过每秒钟创建量 " + this.MAXID);
                }
                tmpid = idHead + id;
            }
            return tmpid;
        }
    }
}
